import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams, ToastController} from 'ionic-angular';
import {TrxnDetailPage} from "../trxn-detail/trxn-detail";
import {PolicyAcctTrxn, Trxn} from "../../../model/pages/policy/policy-detail/policy-acct-trxn";
import {PolicyDetailProvider} from "../../../providers/policy/policy-detail/policy-detail.provider";
import {HttpErrorResponse} from "@angular/common/http";
import {LoadingService} from "../../../services/common/loading.service";

/**
 * Generated class for the AccountListPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
    selector: 'page-account-list',
    templateUrl: 'account-list.html',
    providers: [PolicyDetailProvider, LoadingService]
})
export class AccountListPage {
    /**\
     * 投连账户详情
     * @type {PolicyAcctTrxn}
     */
    accountList: PolicyAcctTrxn = new PolicyAcctTrxn();

    /**
     * 是否在加载数据
     * @type {boolean}
     */
    isLoaded: boolean = false;

    /**
     * 获取数据订阅
     */
    getDataSubscription: any;

    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        private policyDetailProvider: PolicyDetailProvider,
        private toastController: ToastController,
        private loadingService: LoadingService) {
    }

    ionViewDidLoad() {
        // 获取保单id
        let id = this.navParams.get('id');

        if (id != null) {

            // 显示loading动画
            this.loadingService.showLoading();
            // 获取数据
            this.getDataSubscription = this.policyDetailProvider.getPolicyAcctTrxnDetail(id).subscribe(data => {
                if (data) {
                    this.accountList = data;
                    this.isLoaded = true;
                }

                // 加载数据结束
                this.isLoaded = true;

                // 关闭loading动画
                this.loadingService.dismissLoading();
            }, (error: HttpErrorResponse) => {
                // 加载数据结束
                this.isLoaded = true;
                // 关闭loading动画
                this.loadingService.dismissLoading();
            });
        }

    }

    ionViewWillLeave() {
        // 取消订阅数据
        if (this.getDataSubscription) {
            this.getDataSubscription.unsubscribe();
        }
    }

    /**
     * 返回上一级
     */
    goBack() {
        this.navCtrl.pop()
    }

    /***
     * 跳转至投连账户交易明细
     * @param {Array<Trxn>} trxnDetail 明细
     */
    goToTrxnDetailPage(trxnDetail: Array<Trxn>) {
        this.navCtrl.push('TrxnDetailPage', {
            trxnDetail: trxnDetail
        })
    }

}
